<template>
  <div class="flex flex-col flex-1 h-450px">
    <div :id="'editor' + id" class="flex-1 w-full flex-1 overflow-auto"></div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, nextTick, watch, useId } from "vue";
import { debounce } from "lodash-es";

// require styles
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import Quill from "quill";

// @ts-expect-error
import { ImageExtend, QuillWatch } from "quill-image-extend-module";
import QuillResizeImage from "quill-resize-image";

import setting from "@/utils/setting";

Quill.register("modules/ImageExtend", ImageExtend);
Quill.register("modules/resize", QuillResizeImage);

const model = defineModel<string>();

const { placeholder = "请输入..." } = defineProps<{
  placeholder?: string;
}>();

const id = useId();

let editor: any;
let currentContent: string;

// 设置model值
const setModel = debounce((val) => {
  model.value = val;
}, 300);

// 设置值
function setContent() {
  editor?.clipboard.dangerouslyPasteHTML(model.value || "");
}

// 监听mode
watch(
  model,
  (val) => {
    if (currentContent !== val) setContent();
  },
  { immediate: true }
);

onMounted(() => {
  editor = new Quill("#editor" + id, {
    placeholder,
    theme: "snow",
    // debug: 'info',
    modules: {
      // toolbar: true
      toolbar: {
        container: [
          [{ header: [] }], // 标题1、标题2、标题3
          [{ size: ["small", false, "large", "huge"] }], // custom dropdown
          ["bold", "italic", "underline", "strike"], // 粗体、斜体、下划线、删除线
          [{ color: [] }, { background: [] }],
          [{ align: [] }], // 文字对齐方式
          // [{ 'font': [] }],
          [{ list: "ordered" }, { list: "bullet" }], // 有序列表、无序列表
          [{ indent: "-1" }, { indent: "+1" }], // outdent/indent
          [{ direction: "rtl" }], // text direction
          ["link", "image"], // 链接、图片
          ["clean"], // 清除格式
          ["custom-image-size"], // 自定义按钮
        ],
        handlers: {
          "custom-image-size": () => {
            const range = editor.getSelection();

            // 2. 立即用 format 调整宽高
            editor.format(
              range.index,
              1,
              "image",
              { width: "50px", height: "30px" },
              Quill.sources.USER
            );
          },
          image: function () {
            // @ts-expect-error
            QuillWatch.emit(this.quill.id);
          },
          // image: () => {
          //   // chooseMedia();

          //   const range = editor.getSelection(true);
          //   console.log("range", range);

          //   editor.insertEmbed(range.index, "QuillImage", {
          //     src: "https://static.smarbox.cn/cinmoore/images/2025/09/03/2c0ddf5ad3967fd0df8d37f7555e1b10.gif",
          //     width: "50%",
          //     height: "auto",
          //     alt: "示例图片",
          //     style: "border: 1px solid #ccc;",
          //   });
          // },
        },
      },
      ImageExtend: {
        loading: true,
        name: "file",
        action:
          setting.requestHost + setting.requestPath + "/web/v1/tools/upload",

        // 可选参数 设置请求头部
        headers: (xhr) => {
          xhr.setRequestHeader(
            "Authorization",
            "Bearer " + localStorage.getItem("Authorization")
          );
        },
        response: (res) => {
          console.log("res", res);

          return res.data.urls;
        },
      },
      resize: {
        locale: {
          center: "居中",
          floatLeft: "左对齐",
          floatRight: "右对齐",
          restore: "重置",
        },
      },
    },
    // formats: ['italic'],
  });

  nextTick(() => setContent());
  editor.on("text-change", function () {
    const content = editor.root.innerHTML;
    currentContent = content;
    setModel(content);
  });
});
</script>

<style lang="less">
.ql-container {
  overflow: hidden;
  img {
    display: inline;
  }
}

.ql-snow.ql-toolbar {
  .ql-picker.ql-header {
    width: 70px;
    line-height: 22px;

    .ql-picker-label::before,
    .ql-picker-item::before {
      content: "普通";
    }

    .ql-picker-label[data-value="1"]::before,
    .ql-picker-item[data-value="1"]::before {
      content: "标题一";
    }

    .ql-picker-label[data-value="2"]::before,
    .ql-picker-item[data-value="2"]::before {
      content: "标题二";
    }

    .ql-picker-label[data-value="3"]::before,
    .ql-picker-item[data-value="3"]::before {
      content: "标题三";
    }

    .ql-picker-label[data-value="4"]::before,
    .ql-picker-item[data-value="4"]::before {
      content: "标题四";
    }

    .ql-picker-label[data-value="5"]::before,
    .ql-picker-item[data-value="5"]::before {
      content: "标题五";
    }

    .ql-picker-label[data-value="6"]::before,
    .ql-picker-item[data-value="6"]::before {
      content: "标题六";
    }
  }

  .ql-picker.ql-size {
    width: 70px;
    line-height: 22px;

    .ql-picker-label::before,
    .ql-picker-item::before {
      content: "普通";
    }

    .ql-picker-label[data-value="small"]::before,
    .ql-picker-item[data-value="small"]::before {
      content: "小";
    }

    .ql-picker-label[data-value="large"]::before,
    .ql-picker-item[data-value="large"]::before {
      content: "中";
    }

    .ql-picker-label[data-value="huge"]::before,
    .ql-picker-item[data-value="huge"]::before {
      content: "大";
    }
  }
}

// S 链接
.ql-snow .ql-tooltip::before {
  content: "链接" !important;
}

.ql-snow .ql-tooltip a.ql-action::after {
  content: "编辑";
}

.ql-snow .ql-tooltip.ql-editing a.ql-action::after {
  content: "保存";
}

.ql-snow .ql-tooltip a.ql-remove::before {
  content: "移除";
}
// E

#editor-resizer .toolbar {
  top: 0 !important;
}
</style>
